package com.adtech.farmProducts.activities.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.adtech.common.Common;
import com.adtech.common.http.AsyncHttpPostFormData;
import com.adtech.common.http.AsyncHttpResponse;
import com.adtech.common.http.AsyncOkHttpClient;
import com.adtech.common.http.AsyncResponseHandler;
import com.adtech.common.model.RspModel;
import com.adtech.common.utils.FileUtils;
import com.adtech.farmProducts.App;
import com.adtech.farmProducts.R;
import com.adtech.farmProducts.base.BaseActivity;
import com.adtech.farmProducts.base.BaseNfcActivity;
import com.adtech.farmProducts.utils.Constants;
import com.adtech.farmProducts.widget.ClearTextIconEditText;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.google.gson.reflect.TypeToken;
import com.yalantis.ucrop.UCrop;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Author:  xiaocz.
 * Descr:   注册
 */
public class Register2Activity extends BaseNfcActivity {


    /**
     * UI
     */
    @BindView(R.id.root_layout)
    LinearLayout rootLayout;
    @BindView(R.id.gs_name)
    ClearTextIconEditText gs_name;
    @BindView(R.id.gs_type)
    TextView gs_type;
    @BindView(R.id.gs_legal_person)
    ClearTextIconEditText gs_legal_person;
    @BindView(R.id.gs_address)
    ClearTextIconEditText gs_address;

    private String userId;

    /**
     * 显示注册界面
     */
    public static void show(Context context, String userId) {
        Intent intent = new Intent(context, Register2Activity.class);
        intent.putExtra("userId", userId);
        context.startActivity(intent);
    }

    @Override
    protected boolean initArgs(Bundle bundle) {
        if (bundle != null) {
            userId = bundle.getString("userId");
        }
        return userId != null;
    }

    @Override
    protected int getLayoutSourceId() {
        return R.layout.activity_register2;
    }

    @Override
    protected void initWidgets() {
        //addLayoutListener(rootLayout, gs_address);
        super.initWidgets();
    }

    @Override
    protected void initData() {
        super.initData();
        gs_type.setText(cancelReason[0]);
        Collections.addAll(list, cancelReason);
    }

    @BindView(R.id.layout_camera)
    LinearLayout layout_camera;

    @OnClick({R.id.gs_type, R.id.btn_register,R.id.btn_location,R.id.layout_camera})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.gs_type:
                dialogGsType();
                hideKeyboard();
                break;
            case R.id.btn_location:
                hideKeyboard();
                if (Constants.getLocation() != null) {
                    String address=Constants.getLocation().getAddress();
                    if(address!=null){
                        int index=address.indexOf("靠近");
                        gs_address.setText(index>0?address.substring(0,index):address);
                    }
                }else {
                    App.getInstance().showMessage(getResources().getString(R.string.none_location));
                }
                break;
            case R.id.btn_register:
                String gsName = String.valueOf(gs_name.getText()).trim();
                // 校验数据
                if ("".equals(gsName)) {
                    App.getInstance().showMessage("请输入公司名称！");
                    return;
                }
                String gsAddress = String.valueOf(gs_address.getText()).trim();
                if ("".equals(gsAddress)) {
                    App.getInstance().showMessage("请输入公司地址！");
                    return;
                }
                String legalPerson = String.valueOf(gs_legal_person.getText()).trim();
                onRegister(gsName, gsType, legalPerson, gsAddress);
                break;
            case R.id.layout_camera:
                checkAndRequestPermission();
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 如果裁剪错误则直接返回不做任何操作
        if (resultCode == UCrop.RESULT_ERROR) {
            return;
        }
        // 如果有返回值
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case CAMERA_REQUEST_CODE: // 拍照
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        cropRawPhoto(providerUri);
                    } else {
                        cropRawPhoto(mUri);
                    }
                    break;
                case GALLERY_REQUEST_CODE:// 相册选择
                    cropRawPhoto(data.getData());
                    break;
                case CROP_REQUEST_CODE:
                    Uri uri = UCrop.getOutput(data);
                    if (uri != null) {
                        upHeardImage(FileUtils.getFilePathByUri(mContext, uri),layout_camera);
                    } else {
                        App.getInstance().showMessage("获取内容为空！");
                    }
                    break;
                default:
                    break;
            }
        }
    }

    private int gsType = 1;


    private String[] cancelReason = {"生产基地", "批发商", "零售商", "其他"};
    private List<String> list = new ArrayList<>();

    /**
     * 显示-公司类型
     */
    private void dialogGsType() {
        OptionsPickerView<String> optionsPickerView = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                gsType = options1 + 1;
                gs_type.setText(cancelReason[options1]);
            }
        }).setCancelColor(ContextCompat.getColor(mContext, R.color.textColorThird))//取消按钮文字颜色
                .setSubmitColor(ContextCompat.getColor(mContext, R.color.colorPrimary))//确定按钮文字颜色
                .setLineSpacingMultiplier(2f).build();
        optionsPickerView.setTitleText("公司类别");
        optionsPickerView.setPicker(list);
        optionsPickerView.show();
    }

    /**
     * 注册
     */
    private void onRegister(final String gsName, int gsType, String legalPerson, String gsAddress) {
        loadingDialogShow(false);
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        asyncHttpPostFormData.addFormData("companyName", gsName);
        asyncHttpPostFormData.addFormData("companyType", gsType);
        asyncHttpPostFormData.addFormData("legalPerson", legalPerson);
        asyncHttpPostFormData.addFormData("licenseUrl",imageUrl);
        asyncHttpPostFormData.addFormData("address", gsAddress);
        asyncHttpPostFormData.addFormData("userId", userId);
        okHttpClient.posts(Common.Constant.API_IP + "user/bindCompany", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                e.printStackTrace();
                onDismiss();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                onDismiss();
                Type type = new TypeToken<RspModel<String>>() {
                }.getType();
                RspModel<String> rspModel = getAnalysis(response, type, "注册");
                if (rspModel == null) {
                    return;
                }
                switch (rspModel.getCode()) {
                    case 1:
                        showNormalDialog();
                        break;
                    default:
                        App.getInstance().showMessage(rspModel.getMessage());
                        break;
                }
            }
        });
    }

    AlertDialog alertDialog;

    private void showNormalDialog() {
        AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(mContext);
        normalDialog.setTitle("提示");
        normalDialog.setMessage("您已注册企业账号成功?");
        normalDialog.setNegativeButton("去登录",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        alertDialog.dismiss();
                        finish();
                    }
                });
        normalDialog.setPositiveButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        alertDialog.dismiss();
                    }
                });
        alertDialog = normalDialog.show();
    }
}
